package com.tuyan.aixiang.util;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

/**
 * Created by Tim on 17/4/20.
 */

public class SystemUtil {

    /**
     * 得到app版本号
     *
     * @param context
     */
    public static int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
            versionCode = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 得到app版本名称
     *
     * @param context
     */
    public static String getVersionName(Context context) {
        String packageName = context.getApplicationContext().getPackageName();
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "1.0.0";
    }

    /**
     * 调起第三方APP
     *
     * @param context
     * @param packname
     */
    public static void startApp(Context context, String packname) {
        PackageManager packageManager = context.getPackageManager();
        if (checkPackInfo(context, packname)) {
            Intent intent = packageManager.getLaunchIntentForPackage(packname);
            context.startActivity(intent);
        } else {
            ToastUtil.makeShort("没有安装" + packname);
        }
    }

    /**
     * 检查包是否存在
     *
     * @param packname
     * @return
     */
    public static boolean checkPackInfo(Context context, String packname) {
        PackageInfo packageInfo = null;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packname, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return packageInfo != null;
    }
}
